local M = {}

--[[判定文件是否存在， read模式为"r"
	与readFile不同的是不读取文件具体内容
]]
function M.isFileExist(params)
	local base = params.base or system.DocumentsDirectory
	local fileName = params.fileName
	local fileFullPath = system.pathForFile(fileName, base)

	local handle, msg = io.open(fileFullPath, "rb")

	if not handle then
		return false
	else
		io.close(handle)
		handle = nil
		return true
	end
end

--[[ 读取文件
	readMod：常见的模式为"r"和"rb"，如果读取文件的内容不是字符串格式，最好使用rb模式
]]
function M.readFile(params)
	local base = params.base or system.DocumentsDirectory
	local fileName = params.fileName
	local readMod = params.readMod or "rb"
	local fileFullPath = system.pathForFile(fileName, base)

	local handle, msg = io.open(fileFullPath, readMod)

	if not handle then
		print("read file ||" .. fileName .. "|| error:", msg)
		return nil	
	end

	local content = handle:read("*a")
	handle:flush()
	handle:close()
	handle = nil

	return content
end

--[[写入文件
	writeMod：常见摸模式为"w"和"wb"，一般与readMod相匹配，使用rb读取的时候，要使用wb写入
	文件夹路径存在，但是文件不存在将会自动创建文件
	路径不存在的情况下会报错
]]
function M.writeFile(params)
	local fileName = params.fileName
	local fileContent = params.fileContent or ""
	local basePath = params.basePath or system.DocumentsDirectory
	local writeMod = params.writeMod or "wb"
	if type(fileContent) == "table" then
		fileContent = json.encode(fileContent)
	end
	
	local filePath = system.pathForFile(fileName, basePath)

	local handle, msg = io.open(filePath, writeMod)

	if not handle then
		return nil
	end

	handle:write(fileContent)
	handle:flush()
	handle:close()
	handle = nil
end

function M.iterateDir(params)
	local base = params.base or system.DocumentsDirectory
	local path = params.path  -- 相对路径
	local isReadContent = not (params.isReadContent == false)

	local fullPath = system.pathForFile(path, base)

	local fileListener = params.fileListener or function() end
	local dirListener = params.dirListener	or function() end
	
	for fileName in lfs.dir(fullPath) do
		if fileName ~= "." and fileName ~= ".." then
			local mode = lfs.attributes(fullPath .. "/" .. fileName).mode
			if mode and mode == "directory" then
				dirListener(path .. "/" .. fileName)
				iterateDir({
					path = path .. "/" .. fileName, 
					fileListener = fileListener, 
					dirListener = dirListener,
					isReadContent = isReadContent
				})
			else
				local content = ""
				if isReadContent then
					content = readFile(path .. "/" .. fileName, "rb") or ""
				end
				fileListener(fullPath, fileName, content)
			end
		end
	end
end
-- 写入由buffer构成的base64 字符串到本地
function M.writeBufferBase64String(params)
	local fileName = params.fileName
	local fileContent = params.fileContent
	local basePath = params.basePath or system.DocumentsDirectory
	local filePath = system.pathForFile(fileName, basePath)

	local mime = require("mime")
	local ltn12 = require("ltn12")

	ltn12.pump.all(
	  ltn12.source.string(fileContent),
	  ltn12.sink.chain(
	    mime.decode("base64"),
	    ltn12.sink.file(io.open(filePath,"wb"))
	  )
	)
end

return M